package cn.sgy.infrastructure.web.exception.business;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.sgy.infrastructure.convention.error.code.ServiceErrorInfo;
import cn.sgy.infrastructure.convention.error.code.SystemErrorInfo;
import cn.sgy.infrastructure.convention.error.exception.AbstractException;
import cn.sgy.infrastructure.convention.error.exception.ServiceException;
import cn.sgy.infrastructure.convention.error.exception.SystemException;
import cn.sgy.infrastructure.convention.result.Result;
import cn.sgy.infrastructure.convention.result.Results;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Optional;
import java.util.Set;

/**
 * @author sgy
 * @description 全局异常处理器
 * @date 2023-02-28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 拦截参数验证异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result validExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        FieldError firstFieldError = CollectionUtil.getFirst(bindingResult.getFieldErrors());
        String exceptionStr = Optional
                .ofNullable(firstFieldError)
                .map(FieldError::getDefaultMessage)
                .orElse(StrUtil.EMPTY);
        log.warn("[参数校验异常] 详细信息=[{}]", buildData(request, exceptionStr));
        return Results.failure(ServiceErrorInfo.ARGUMENT_VALIDATION_ERROR.code(), exceptionStr);
    }

    /**
     * 拦截参数验证异常
     */
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public Result handleBindException(HttpServletRequest request, ConstraintViolationException exs) {
        Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            log.warn("[参数校验异常] 详细信息=[{}]", buildData(request, item.getMessage()), exs);
            return Results.failure(ServiceErrorInfo.ARGUMENT_VALIDATION_ERROR.code(), item.getMessage());
        }
        return Results.failure(ServiceErrorInfo.ARGUMENT_VALIDATION_ERROR);
    }

    /**
     * 拦截自定义异常
     */
    @ExceptionHandler(value = {AbstractException.class})
    public Result handleCustomException(HttpServletRequest request, AbstractException ex) {
        return Results.failure(ex);
    }

    /**
     * 拦截自定义的系统异常
     */
    @ExceptionHandler(value = {SystemException.class})
    public Result handleClientException(HttpServletRequest request, SystemException ex) {
        return Results.failure(ex);
    }

    /**
     * 拦截自定义的服务异常
     */
    @ExceptionHandler(value = {ServiceException.class})
    public Result handleServiceException(HttpServletRequest request, ServiceException ex) {
        return Results.failure(ex);
    }

    /**
     * 拦截未捕获异常
     */
    @ExceptionHandler(value = Throwable.class)
    public Result handleThrowable(HttpServletRequest request, Throwable throwable) {
        log.error("系统异常 详细信息=[{}]", buildData(request, null), throwable);
        return Results.failure(SystemErrorInfo.SYSTEM_ERROR);
    }

    private String getUrl(HttpServletRequest request) {
        if (StringUtils.isEmpty(request.getQueryString())) {
            return request.getRequestURL().toString();
        }
        return request.getRequestURL().toString() + "?" + request.getQueryString();
    }

    private String buildData(HttpServletRequest request, Object msg) {
        JSONObject data = new JSONObject();
        data.set("method", request.getMethod());
        data.set("url", getUrl(request));
        data.set("msg", msg);
        return data.toString();
    }
}
